package cn.openea.perpartner.meily.web.service.importandexport;

import cn.openea.perpartner.common.core.exception.ServiceException;
import cn.openea.perpartner.common.core.utils.StringUtils;
import cn.openea.perpartner.common.core.utils.poi.ExcelUtil;
import cn.openea.perpartner.meily.constant.CommonConstants;
import cn.openea.perpartner.meily.web.entity.Enterprise;
import cn.openea.perpartner.meily.web.entity.dto.EnterpriseDtoFactory.ImportTemplateDto;
import cn.openea.perpartner.meily.web.entity.dto.ImportErrMsgDTO;
import cn.openea.perpartner.meily.web.entity.vo.ExportDataVo;
import cn.openea.perpartner.meily.web.service.IEnterpriseService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ysk
 * @version 1.0.1
 * @Description 企业导入处理器
 * @createTime 2023年06月28日 00:39:00
 */
@Slf4j
@Service(value = CommonConstants.IMPORTANDEXPORT.ENTERPRISE_IMPORT)
public class EnterpriseImportService extends ImportAndExportAbstractService {

    @Resource
    private IEnterpriseService enterpriseService;

    @Override
    public void exportExcel(ExportDataVo exportDataVo, HttpServletResponse response) {
        // 导出模板
        List<ImportTemplateDto> list = new ArrayList<>();
        ExcelUtil<ImportTemplateDto> util = new ExcelUtil<>(ImportTemplateDto.class);
        util.exportExcel(response, list, "企业导入数据模板");
    }

    @Override
    public ImportErrMsgDTO handleSingleExcel(@NonNull Object obj) {
        if (!(obj instanceof ImportTemplateDto)) {
            throw new ServiceException("数据异常");
        }
        ImportTemplateDto importTemplateDto = (ImportTemplateDto) obj;
        Enterprise enterprise = new Enterprise();
        BeanUtils.copyProperties(importTemplateDto, enterprise);
        // 生成指定编号
        if (importTemplateDto.getRegisterDate() != null) {
            enterprise.setEstablishmentDate(importTemplateDto.getRegisterDate()
                    .toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate());
        }
        enterprise.setEnterpriseNo(StringUtils.getDigitalCoding(18, "EP"));
        try {
            enterpriseService.addEnterprise(enterprise);
        } catch (Exception e) {
            e.printStackTrace();
            return ImportErrMsgDTO.builder()
                    .id(enterprise.getEnterpriseName())
                    .errMsg(e.getMessage())
                    .build();
        }
        return null;
    }
}
